package com.jade.store.wechat.biz.service.auth;

import com.jade.framework.base.context.ApplicationContextUtils;
import com.jade.framework.cache.CacheService;
import com.jade.store.wechat.biz.common.Configure;
import com.jade.store.wechat.biz.common.Util;
import com.jade.store.wechat.biz.common.WxConstantUtil;
import com.jade.store.wechat.biz.protocol.auth.ComponentAccessTokenReq;
import com.jade.store.wechat.biz.protocol.auth.ComponentAccessTokenRes;
import com.jade.store.wechat.biz.service.BaseService;

/**
 * Created with IntelliJ IDEA.
 * User: jinya
 * Date: 2016/12/13
 * Time: 18:09
 * TEL :17701640710   MAIL:2009_jinya@163.com
 * To change this template use File | Settings | File Templates.
 */
public class ApiComponentTokenService extends BaseService {
   private CacheService cacheService = ApplicationContextUtils.getBean("system_cacheService");
    public ApiComponentTokenService() throws IllegalAccessException, InstantiationException, ClassNotFoundException {
        super(WxConstantUtil.api_component_access_token);
    }
    /**
     * 请求获取Token服务
     * @param
     * @return API返回的数据
     * @throws Exception
     */
    public String getAccessToken() throws Exception {
      //  Object obj=cacheService.get(WxConstantUtil.cache_component_access_token);
        //  if(obj==null){
            ComponentAccessTokenReq req=new ComponentAccessTokenReq();
            req.setComponent_appid(Configure.appID);
            req.setComponent_appsecret(Configure.appSecret);
            req.setComponent_verify_ticket(getTicket());
            String responseString = sendJsonPost(req);
            ComponentAccessTokenRes res = (ComponentAccessTokenRes) Util.getObjectFromJson(responseString, ComponentAccessTokenRes.class);
            cacheService.set(WxConstantUtil.cache_component_access_token, res.getComponent_access_token(), 7000);
            return res.getComponent_access_token();
        //}else{
        //  return obj.toString();
        // }
    }
    private String getTicket(){
        String result="";
        Object obj=cacheService.get(WxConstantUtil.cache_component_verify_ticket);
        if(obj!=null){
            result=obj.toString();
        }
        return result;
    }
}
